package fm.last.time.stats;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import android.util.Base64;
import android.util.Log;

public class AuthenticationRequester extends LastFmRequester {

	private static final String METHOD = "auth.getMobileSession";

	public static final String USERNAME_KEY = "username";

	public static final String AUTH_TOKEN_KEY = "authToken";
	

	public static final String API_SIG_KEY = "api_sig";

	
	public AuthenticationRequester() {
		super(METHOD);
		// TODO Auto-generated constructor stub
	}

	@Override
	protected String doInBackground(String... params) {
		String userName = params[0];
		String password = params[1];
		String apiKey = params[2];
		String secret = params[3];
		String authToken = md5(userName + md5(password));
		Map<String, String> parameters = new HashMap<String, String>();
		parameters.put(AUTH_TOKEN_KEY, authToken);
		parameters.put(API_KEY_KEY, apiKey);
		parameters.put(USERNAME_KEY, userName);
		parameters.put(METHOD_KEY, METHOD);
		String apiSig = md5(makeSignatureString(parameters )+secret);
		parameters.put(FORMAT, JSON);
		parameters.remove(METHOD_KEY);
		parameters.put(API_SIG_KEY, apiSig);
		String data ="";
		try {
			StringBuilder json = new StringBuilder();
            BufferedReader reader = 
                new BufferedReader(
                            new InputStreamReader(getData(parameters)));
            String line = reader.readLine();
            while (line != null){
                json.append(line);
                line = reader.readLine();
            }
			data = json.toString();
            Log.e("lastfmstats", data);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return data;
	}
	

	
}
